package models;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

@Entity
@DiscriminatorValue(value="1")
public class Establishment extends Place {
	enum OrderType {
		SINGLE,
		MULTIPLE
	}

	@Column(nullable=false)
	private OrderType orderType = OrderType.SINGLE;
	
	@OneToMany(cascade=CascadeType.PERSIST, mappedBy="establishment", fetch=FetchType.LAZY)
	private Set<Order> orders;
	
	@OneToOne(cascade=CascadeType.ALL, mappedBy="establishment", fetch=FetchType.LAZY)
	private Menu menu;
	
	@OneToOne(cascade=CascadeType.ALL, mappedBy="establishment", fetch=FetchType.LAZY)
	private SpotConfiguration spotConfiguration;

	public Set<Order> getOrders() {
		return orders;
	}

	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public OrderType getOrderType() {
		return orderType;
	}

	public void setOrderType(OrderType orderType) {
		this.orderType = orderType;
	}
	
	@Override
	protected String getType() {
		return "single";
	}

	public SpotConfiguration getSpotConfiguration() {
		return spotConfiguration;
	}

	public void setSpotConfiguration(SpotConfiguration spotConfiguration) {
		this.spotConfiguration = spotConfiguration;
	}
	
	@Override
	public JsonSerializer<Establishment> getPlaceSerializer() {
		return new EstablishmentJsonSerializer();
	}
	
	@Override
	public JsonSerializer<Collection<Establishment>> getPlacesSerializer() {
		return new EstablishmentsJsonSerializer();
	}
	
	public static class EstablishmentsJsonSerializer extends PlacesJsonSerializer<Establishment> {
		@Override
		public JsonElement serialize(Collection<Establishment> establishments, Type type,
				JsonSerializationContext context) {
			return super.serialize(establishments, type, context);
		}
	}
	
	public static class EstablishmentJsonSerializer extends PlaceJsonSerializer<Establishment> {
		@Override
		public JsonElement serialize(Establishment establishment, Type type,
				JsonSerializationContext context) {
			JsonObject json = (JsonObject) super.serialize(establishment, type, context);
			JsonObject menu =  new JsonObject();
			menu.addProperty("id", establishment.getMenu().getId());
			menu.addProperty("picture", establishment.getMenu().getPicture().getURL());
			return json;
		}
	}
}
